<template>
  <Drawer
      title="CSV数据源编辑"
      v-model="visible"
      width="530"
      :mask-closable="false"
      :styles="$PnUtil.buildDrawerStyleByHasFooter()">
    <Spin fix v-show="readCsvContentLoading">
      <Icon type="ios-loading" size=18 class="spin-icon-load"></Icon>
      <div>解析CSV数据中，请耐心等待...</div>
    </Spin>
    <Alert type="info" show-icon style="padding-right: 10px;">
      说明：点击<a href="javascript:;" @click="templateModalVisible = !templateModalVisible"> 此处 </a>显示文件示例
    </Alert>
    <Form ref="form" :label-width="120" :model="formData" :rules="ruleValidate">
      <FormItem label="id" prop="id" hidden>
        <Input v-model="formData.id"/>
      </FormItem>
      <FormItem label="CSV数据源名称" prop="name">
        <Input v-model="formData.name" placeholder="请输入CSV数据源名称" :disabled="formData.id != ''"/>
      </FormItem>

      <FormItem label="文件上传">
        <Alert v-if="type == 'edit'" type="warning" style="padding: 10px;">
          如需要重新上传新的文件并解析，请确保当前数据源明没有被任何组件关联使用，否则新解析的数据会覆盖原本的数据，造成被关联的组件无法正常使用数据源结果集
        </Alert>
        <Upload
            ref="upload"
            :show-upload-list="false"
            type="drag"
            name="file"
            :action="uploadAction"
            :headers="{Authorization: token}"
            :data="{pageId: 'csv_datasources'}"
            :accept="'.csv,.xls,.xlsx'"
            :format="['csv','xls','xlsx']"
            :max-size="5120"
            :on-success="uploadSuccessHandle"
            :on-format-error="uploadFormatError"
            :on-exceeded-size="uploadExceededSize">
          <div style="padding: 30px 0">
            <p>支持格式：csv，xls，xlsx；文件大小限制：5MB</p>
            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
            <p>点击或拖拽文件到这里进行文件上传</p>
          </div>
        </Upload>
      </FormItem>

      <FormItem label="解析结果" prop="json_data">
        <CodeEditor v-model="formData.json_data" mode="json"></CodeEditor>
      </FormItem>

      <FormItem label="备注" prop="remark">
        <Input type="textarea" :rows="4" v-model="formData.remark"/>
      </FormItem>

    </Form>

    <Modal
        v-model="templateModalVisible"
        title="CSV文件示例"
        :mask="true"
        :z-index="999"
        :transfer="true">
      <img src="./image/csv_example.png" style="width: 490px; box-shadow: 0px 0px 8px #000;"/>
      <div slot="footer">
        <Button type="default" @click="templateModalVisible = false">关闭</Button>
      </div>
    </Modal>

    <DrawerFooter>
      <Button class="m-r-5px" @click="visible = false">关闭</Button>
      <Button type="primary" @click="submitForm" :loading="loading">保存</Button>
    </DrawerFooter>
  </Drawer>
</template>

<script>
import ManageMixin from "@/mixin/ManageMixin";

export default {
  name: 'CsvDatasourceForm',
  mixins: [ManageMixin],
  data() {
    return {
      visible: false,
      loading: false,
      type: '',
      readCsvContentLoading: false,
      token: localStorage.getItem('token'),
      formData: {
        id: '',
        name: '',
        json_data: '',
        remark: ''
      },
      ruleValidate: {
        name: [
          {required: true, message: 'CSV数据源名称不能为空', trigger: 'blur'}
        ]
      },

      uploadAction: window.g.AXIOS_BASE_URL + '/file/upload',
      templateModalVisible: false
    }
  },
  mounted() {

  },
  methods: {
    init(type, id) {
      this.type = type
      this.visible = true
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        if (type == 'edit') {
          this.$PnApi.CsvDatasourceApi.getCsvDatasourceById(id).then(result => {
            this.formData = this.recover(this.formData, result.data.payload)
          })
        }
      })
    },
    uploadSuccessHandle(result) {
      if (result.success) {
        this.$Message.success(result.message)
        let fileName = result.payload.filename;
        this.readCsvContentLoading = true
        this.$PnApi.CsvDatasourceApi.parseCsvOrExcel(fileName, 'csv_datasources').then(result => {
          if (result.data.success) {
            this.formData.json_data = JSON.stringify(result.data.payload, null, 2);
          } else {
            this.$Message.error(result.data.message)
          }
          this.readCsvContentLoading = false
        }).catch(error => {
          this.$Message.error("文件内容解析失败")
          this.readCsvContentLoading = false
        })
      } else {
        this.$Message.error(result.message)
      }
    },

    /**
     * 上传文件格式错误
     */
    uploadFormatError() {
      this.$Message.warning({
        duration: 5,
        content: '上传文件格式错误，只支持（.csv,.xls,.xlsx）格式文件'
      })
    },

    /**
     * 上传文件大小超出限制
     */
    uploadExceededSize() {
      this.$Message.warning({
        duration: 5,
        content: '上传文件大小超出限制，上传文件不能超过5MB'
      })
    },

    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          this.$PnApi.CsvDatasourceApi.saveCsvDatasource(this.formData).then(result => {
            if (result.data.success) {
              this.visible = false
              this.$Message.success(result.data.message)
              this.$emit("refreshDataList")
            } else {
              this.$Message.error(result.data.message)
            }
            this.loading = false
          })
        }
      });
    }
  },
  computed: {}
}
</script>

<style scoped>
>>> .ivu-form-item-content {
  line-height: initial !important;
}

.spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}

@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
